package org.usmile.algorithms.learn.graph.bfs;

import org.usmile.algorithms.learn.graph.AdjList;
import org.usmile.algorithms.learn.graph.Graph;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class GraphBFS {
    public List<Integer> bfs(Graph graph) {
        if (graph == null) {
            return new ArrayList<>();
        }

        List<Integer> result = new ArrayList<>();
        Queue<Integer> queue = new LinkedList<>();
        boolean[] visited = new boolean[graph.getV()];
        for (int v = 0; v < graph.getV(); v++) {
            if (!visited[v]) {
                queue.offer(v);
                visited[v] = true;
                while (!queue.isEmpty()) {
                    int curr = queue.poll();
                    result.add(curr);
                    for (int w : graph.adj(curr)) {
                        if (!visited[w]) {
                            queue.add(w);
                            visited[w] = true;
                        }
                    }
                }
            }
        }

        return result;
    }

    public static void main(String[] args) {
        Graph graph = new AdjList(8);
        graph.addEdge(0, 1);
        graph.addEdge(1, 2);
        graph.addEdge(1, 4);
        graph.addEdge(3, 2);

        System.out.println(new GraphBFS().bfs(graph));
    }
}
